package com.wao.base.util;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Created by Arthur on 2017/4/13.
 */
public class SnowFlakeUtil {

    /**
     * 起始的时间戳 2017-01-01 00:00:00.000
     */
    private final static long START_STMP = 1483200000000L;
    /**
     * 活动总位数
     */
    private final static long TOTAL_BIT = 22;

    /**
     * 每一部分占用的位数
     */
    private final static long MACHINE_BIT = 5;   //机器标识占用的位数
    private final static long DATACENTER_BIT = 5;//数据中心占用的位数

    private static long sequence = 0L; //序列号
    private static long lastStmp = -1L;//上一次时间戳
    private static long localIpAddressValue;

    static {
        localIpAddressValue = localIpAddressValue();
    }

    /**
     * 产生下一个ID
     *
     * @return
     */
    public static long nextId() {
        return nextId(DATACENTER_BIT, MACHINE_BIT);                             //序列号部分
    }

    /**
     * 产生下一个ID
     *
     * @return
     */
    public static synchronized long nextId(long datacenterBit, long machineBit) {
        if (datacenterBit + machineBit > TOTAL_BIT) {
            throw new RuntimeException("The sum of DatacenterBit and MachineBit cannot be greater than TOTAL_BIT");
        }
        long currStmp = getNewstmp();
        if (currStmp < lastStmp) {
            throw new RuntimeException("Clock moved backwards.  Refusing to generate id");
        }

        if (currStmp == lastStmp) {
            //相同毫秒内，序列号自增
            sequence = (sequence + 1) & maxNum(TOTAL_BIT - datacenterBit - machineBit);
            //同一毫秒的序列数已经达到最大
            if (sequence == 0L) {
                currStmp = getNextMill();
            }
        } else {
            //不同毫秒内，序列号置为0
            sequence = 0L;
        }

        lastStmp = currStmp;

        return (currStmp - START_STMP) << (TOTAL_BIT) //时间戳部分
                | getDatacenterId(datacenterBit, machineBit) << (TOTAL_BIT - datacenterBit)  //数据中心部分
                | getMachineId(machineBit) << (TOTAL_BIT - datacenterBit - machineBit)  //机器标识部分
                | sequence; //序列号部分
    }

    private static long getNextMill() {
        long mill = getNewstmp();
        while (mill <= lastStmp) {
            mill = getNewstmp();
        }
        return mill;
    }

    private static long getNewstmp() {
        return System.currentTimeMillis();
    }

    private static long maxNum(long bit) {
        return -1L ^ (-1L << bit);
    }

    private static long getDatacenterId(long datacenterBit, long machineBit) {
        if (localIpAddressValue < 0)
            localIpAddressValue = localIpAddressValue();
        return (long) ((localIpAddressValue >> machineBit) & maxNum(datacenterBit));
    }

    private static long getMachineId(long machineBit) {
        if (localIpAddressValue < 0)
            localIpAddressValue = localIpAddressValue();
        return (long) (localIpAddressValue & maxNum(machineBit));
    }

    private static long localIpAddressValue() {
        InetAddress address;
        try {
            address = InetAddress.getLocalHost();
        } catch (final UnknownHostException e) {
            throw new IllegalStateException("Cannot get LocalHost InetAddress, please check your network!");
        }
        byte[] ipAddressByteArray = address.getAddress();
        return ipAddressByteArray[ipAddressByteArray.length - 1]
                + (ipAddressByteArray[ipAddressByteArray.length - 2] << 8)
                + (ipAddressByteArray[ipAddressByteArray.length - 3] << 16)
                + (ipAddressByteArray[ipAddressByteArray.length - 4] << 24);
    }


    public static void main(String[] args) {
        long count = 1000;
        for (int i = 0; i < (1 << 12); i++) {
            long nextId = SnowFlakeUtil.nextId();
            String byteStr = Long.toBinaryString(nextId);

            System.out.println("【" + (count++) + "】 " + nextId + " " + byteStr.substring(0, byteStr.length() - 22) + " "
                    + byteStr.substring(byteStr.length() - 22, byteStr.length() - 17) + " "
                    + byteStr.substring(byteStr.length() - 17, byteStr.length() - 12) + " "
                    + byteStr.substring(byteStr.length() - 12, byteStr.length()));
        }

    }

}
